package com.tanjie.blackbean.schedule;

import com.tanjie.blackbean.schedule.properties.ScheduleConfigProperties;
import com.tanjie.blackbean.schedule.support.BlackbeanSchedule;
import com.tanjie.blackbean.schedule.support.ScheduledFutureHolder;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import java.util.List;

/**
 * @Author tanjie
 * @Date 2022/6/23 下午2:02 周四
 **/
@Slf4j
@AllArgsConstructor
@Configuration
@EnableConfigurationProperties(value = {ScheduleConfigProperties.class})
public class BlackbeanScheduleAutoConfiguration {

    ScheduleConfigProperties properties;

    @Bean("scheduleThreadPoolTaskScheduler")
    @ConditionalOnProperty(prefix = "blackbean.schedule", name = {"enable"}, havingValue = "true")
    public ThreadPoolTaskScheduler scheduleThreadPoolTaskScheduler() {
        // 获取配置信息
        List<ScheduleConfigProperties.ScheduleConfig> scheduleConfigs = properties.getScheduleConfigList();
        int poolSize = 10;
        if (scheduleConfigs != null && scheduleConfigs.size() > 0) {
            poolSize = scheduleConfigs.size();
        }
        String threadNamePrefix = properties.getThreadNamePrefix();
        // 创建ThreadPoolTaskScheduler
        ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
        threadPoolTaskScheduler.setPoolSize(poolSize);
        threadPoolTaskScheduler.setThreadNamePrefix(threadNamePrefix);
        return threadPoolTaskScheduler;
    }

    @Bean
    public ScheduledFutureHolder scheduledFutureHolder() {
        return new ScheduledFutureHolder();
    }

    @Bean
    public BlackbeanSchedule blackbeanSchedule() {
        return new BlackbeanSchedule(scheduleThreadPoolTaskScheduler(), properties, scheduledFutureHolder());
    }

}

